from ruamel import yaml
from common.settings import logger
from utils.otherUtils.file_control import check_file_path
from common.constant import ApiInfo, CommonErrorInfo, YamlHandlerErrorInfo, CommonInfo


class YamlHandler:

    def __init__(self, api_common_info_file_path: str = None, api_file_path: str = None, project_name: str = None,
                 api_name: str = None):
        self.api_common_info_file_path = api_common_info_file_path
        self.api_file_path = api_file_path
        self.project_name = project_name
        self.api_name = api_name
        self.api_common_info = {}

    @staticmethod
    def read_yaml_file(file_path: str) -> dict:
        file_path = check_file_path(file_path)
        with open(file_path, 'r', encoding='utf-8') as file:
            return yaml.load(file, Loader=yaml.RoundTripLoader)

    def get_api_common_info(self) -> None:
        api_common_info = self.read_yaml_file(self.api_common_info_file_path)
        if self.project_name:
            if self.project_name not in api_common_info.keys():
                logger.error(CommonErrorInfo.PROJECT_NAME_NOT_EXISTS.value)
                raise ValueError(CommonErrorInfo.PROJECT_NAME_NOT_EXISTS.value)
            self.api_common_info = api_common_info[self.project_name]
        else:
            logger.error(CommonErrorInfo.PROJECT_NAME_IS_NONE.value)
            raise ValueError(CommonErrorInfo.PROJECT_NAME_IS_NONE.value)

    def get_api_info(self) -> dict:
        all_api_info = self.read_yaml_file(self.api_file_path)
        if self.api_name:
            if self.api_name not in all_api_info.keys():
                logger.error(CommonErrorInfo.API_NAME_NOT_EXISTS.value)
                raise ValueError(CommonErrorInfo.API_NAME_NOT_EXISTS.value)
            if self.api_common_info:
                host = self.api_common_info.get(ApiInfo.HOST.value)
                cookie = self.api_common_info.get(ApiInfo.COOKIE.value)
                if host and cookie:
                    all_api_info[self.api_name][ApiInfo.HOST.value] = host
                    all_api_info[self.api_name][ApiInfo.HEADERS.value][ApiInfo.COOKIE.value] = cookie
                    all_api_info[self.api_name][ApiInfo.HEADERS.value][ApiInfo.USER_AGENT.value] = \
                        CommonInfo.USER_AGENT_VALUE.value
                    return all_api_info[self.api_name]
                else:
                    logger.error(YamlHandlerErrorInfo.HOST_OR_COOKIE_IS_NONE.value)
                    raise ValueError(YamlHandlerErrorInfo.HOST_OR_COOKIE_IS_NONE.value)
            else:
                logger.error(YamlHandlerErrorInfo.API_COMMON_INFO_IS_NONE.value)
                raise ValueError(YamlHandlerErrorInfo.API_COMMON_INFO_IS_NONE.value)
        else:
            logger.error(CommonErrorInfo.API_NAME_IS_NONE.value)
            raise ValueError(CommonErrorInfo.API_NAME_IS_NONE.value)

    def run(self) -> dict:
        self.get_api_common_info()
        return self.get_api_info()
